package service

import (
	"context"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/share309/gojwt"
	"time"
	"user_srv/basic/config"
	__ "user_srv/basic/userproto"
	"user_srv/handler/dao"
	"user_srv/handler/models"
	"user_srv/pkg/export"
)

type Server struct {
	__.UnimplementedUserServer
}

func (s *Server) ListPhoneStatus(_ context.Context, in *__.ListPhoneStatusReq) (*__.ListPhoneStatusResp, error) {
	status, err := dao.ListPhoneStatus(in)
	if err != nil {
		return nil, err
	}
	phoneStatus, err := status.ListPhoneStatus()
	if err != nil {
		return nil, errors.New("获取手机号状态列表失败" + err.Error())
	}
	var listPhoneStatus []*__.Status
	for _, v := range phoneStatus {
		listPhoneStatus = append(listPhoneStatus, &__.Status{
			Id:              v.Id,
			VipName:         v.VipName,
			Mobile:          v.Mobile,
			Time:            v.Time,
			Terminal:        v.Terminal,
			LssueType:       v.LssueType,
			FeedbackContent: v.FeedbackContent,
			PhoneStatus:     int64(v.PhoneStatus),
		})
	}
	return &__.ListPhoneStatusResp{
		List: listPhoneStatus,
	}, nil
}

func (s *Server) List(_ context.Context, in *__.ListReq) (*__.ListResp, error) {
	user := models.UserFeedback{}
	list, err := user.UserFeedbackList(int(in.Page), int(in.PageSize))
	if err != nil {
		return nil, err
	}
	var listUsers []*__.ListUser
	for _, v := range list {
		listUsers = append(listUsers, &__.ListUser{
			Id:              v.Id,
			VipName:         v.VipName,
			Mobile:          v.Mobile,
			Time:            v.Time,
			Terminal:        v.Terminal,
			LssueType:       v.LssueType,
			FeedbackContent: v.FeedbackContent,
			PhoneStatus:     int64(v.PhoneStatus),
		})
	}
	return &__.ListResp{
		List: listUsers,
	}, nil
}

// 获取手机号列表
func (s *Server) ListMobile(_ context.Context, in *__.ListMobileReq) (*__.ListMobileResp, error) {
	mobile, err := dao.ListMobile(in)
	if err != nil {
		return nil, err
	}
	mobiles, err := mobile.GetMobiles()
	if err != nil {
		return nil, errors.New("获取手机号列表失败" + err.Error())
	}
	var listMobile []*__.Mobile
	for _, v := range mobiles {
		listMobile = append(listMobile, &__.Mobile{
			Id:              v.Id,
			VipName:         v.VipName,
			Mobile:          v.Mobile,
			Time:            v.Time,
			Terminal:        v.Terminal,
			LssueType:       v.LssueType,
			FeedbackContent: v.FeedbackContent,
			PhoneStatus:     int64(v.PhoneStatus),
		})
	}
	return &__.ListMobileResp{
		List: listMobile,
	}, nil
}

// 获取终端列表
func (s *Server) ListTerminal(_ context.Context, in *__.ListTerminalReq) (*__.ListTerminalResp, error) {
	terminal, err := dao.ListTerminal(in)
	if err != nil {
		return nil, err
	}
	Terminal, err := terminal.ListTerminal()
	if err != nil {
		return nil, errors.New("获取终端列表失败" + err.Error())
	}

	var listTerminals []*__.Terminal
	for _, v := range Terminal {
		listTerminals = append(listTerminals, &__.Terminal{
			Id:              v.Id,
			VipName:         v.VipName,
			Mobile:          v.Mobile,
			Time:            v.Time,
			Terminal:        v.Terminal,
			LssueType:       v.LssueType,
			FeedbackContent: v.FeedbackContent,
			PhoneStatus:     int64(v.PhoneStatus),
		})
	}
	return &__.ListTerminalResp{
		List: listTerminals,
	}, nil
}

// 发送短信
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	err := dao.SendSms(in)
	if err != nil {
		return nil, errors.New("发送短信失败123" + err.Error())
	}
	return &__.SendSmsResp{
		Message: "发送成功",
	}, nil
}

// 注册用户
func (s *Server) RegisterUser(_ context.Context, in *__.RegisterUserReq) (*__.RegisterUserResp, error) {
	user, err := dao.RegisterUser(in)
	if err != nil {
		return nil, errors.New("注册失败" + err.Error())
	}

	return &__.RegisterUserResp{
		Id: int32(user.Id),
	}, nil
}

// 登录用户
func (s *Server) LoginUser(_ context.Context, in *__.LoginUserReq) (*__.LoginUserResp, error) {
	user, err := dao.LoginUser(in)
	if err != nil {
		return nil, err
	}
	token, err := gojwt.NewJWT(config.KEY_JWT).CreateToken(gojwt.CustomClaims{
		ID: uint(user.Id),
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: time.Now().Unix() + 86400*7,
		},
	})
	if err != nil {
		return nil, errors.New("token生成失败" + err.Error())
	}
	return &__.LoginUserResp{
		Id:       int32(user.Id),
		Message:  "登录成功",
		Token:    token,
		UserRole: int64(user.UserRole),
	}, nil
}

// 创建用户钱包
func (s *Server) UserWallet(_ context.Context, in *__.UserWalletReq) (*__.UserWalletResp, error) {
	user, err := dao.UserWallet(in)
	if err != nil {
		return nil, errors.New("创建用户钱包失败" + err.Error())
	}
	return &__.UserWalletResp{
		Id: int32(user.Id),
	}, nil
}

// 创建个人用户信息
func (s *Server) IndividualUser(_ context.Context, in *__.IndividualUserReq) (*__.IndividualUserResp, error) {

	user, err := dao.IndividualUser(in)
	if err != nil {
		return nil, errors.New("创建用户失败" + err.Error())
	}

	return &__.IndividualUserResp{
		Id: int32(user.Id),
	}, nil
}

// 保存用户消费信息
func (s *Server) UserConsumptionInformation(_ context.Context, in *__.UserConsumptionInformationReq) (*__.UserConsumptionInformationResp, error) {
	user, err := dao.UserConsumptionInformation(in)
	if err != nil {
		return nil, errors.New("创建消费记录失败")
	}
	return &__.UserConsumptionInformationResp{
		Id: int32(user.Id),
	}, nil
}

// 发票添加
func (s *Server) UserInvoice(_ context.Context, in *__.UserInvoiceReq) (*__.UserInvoiceResp, error) {
	user, err := dao.UserInvoice(in)
	if err != nil {
		return nil, errors.New("创建发票失败123" + err.Error())
	}
	return &__.UserInvoiceResp{
		Id: int32(user.Id),
	}, nil
}

// 发票详情
func (s *Server) UserInvoiceDetail(_ context.Context, in *__.UserInvoiceDetailReq) (*__.UserInvoiceDetailResp, error) {
	invoice, err := dao.UserInvoiceDetail(in)
	if err != nil {
		return nil, errors.New("发票不存在")
	}
	return &__.UserInvoiceDetailResp{
		Id:                      int32(invoice.Id),
		Name:                    invoice.Name,
		TaxIdentificationNumber: invoice.TaxIdentificationNumber,
		Address:                 invoice.Address,
		Mobile:                  invoice.Mobile,
		BankOfDeposit:           invoice.BankOfDeposit,
		BankAccount:             invoice.BankAccount,
	}, nil
}

// 个人用户详情
func (s *Server) UserindelDetail(_ context.Context, in *__.UserindelDetailReq) (*__.UserindelDetailResp, error) {
	user, err := dao.UserindelDetail(in)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	return &__.UserindelDetailResp{
		Id:                  int32(user.Id),
		Name:                user.Name,
		Mobile:              user.Mobile,
		EnterpriseUser:      user.EnterpriseUser,
		MemberLevel:         user.MemberLevel,
		UserPrice:           float32(user.UserPrice), // Convert float64 to float32
		RegistrationChannel: user.RegistrationChannel,
		RegisterTime:        user.RegisterTime.Format("2006-01-02 15:04:05"),
		LastLoginTime:       user.LastLoginTime.Format("2006-01-02 15:04:05"),
	}, nil
}

// 个人用户消费详情
func (s *Server) UserConsumptionInformationDetail(_ context.Context, in *__.UserConsumptionInformationDetailReq) (*__.UserConsumptionInformationDetailResp, error) {
	user, err := dao.UserConsumptionInformationDetail(in)
	if err != nil {
		return nil, errors.New("用户不存在")
	}
	return &__.UserConsumptionInformationDetailResp{
		Id:                        int32(user.Id),
		UserId:                    user.UserId,
		PayNo:                     user.PayNo,
		Event:                     user.Event,
		PriceTime:                 user.PriceTime.Format("2006-01-02 15:04:05"),
		OrderNo:                   user.OrderNo,
		GiftAmount:                user.GiftAmount,
		RechargeAmountPrincipal:   user.RechargeAmountPrincipal,
		TotalRechargeAmount:       user.TotalRechargeAmount,
		RefundAmount:              user.RefundAmount,
		TotalOrderPrice:           float32(user.TotalOrderPrice),
		MonthlyOrderPaymentAmount: user.MonthlyOrderPaymentAmount,
	}, nil
}

// RealName 处理用户实名认证请求
func (s *Server) RealName(_ context.Context, in *__.RealNameReq) (*__.RealNameResp, error) {
	// 调用DAO层的实名认证方法
	user, err := dao.RealName(in)
	if err != nil {
		// 返回清晰的错误信息
		return nil, errors.New("实名认证失败: " + err.Error())
	}

	// 认证成功，返回用户ID和成功消息
	return &__.RealNameResp{
		Id:      int64(user.Id),
		Message: "实名认证成功",
	}, nil
}

// 发票号码查询
func (s *Server) ListTaxIdentificationNumber(_ context.Context, in *__.ListTaxIdentificationNumberReq) (*__.ListTaxIdentificationNumberResp, error) {
	list, err := dao.ListTaxIdentificationNumber(in)
	if err != nil {
		return nil, err
	}
	taxIdentification, err := list.GetTaxIdentificationNumber()
	if err != nil {
		return nil, errors.New("发票号码查询失败" + err.Error())
	}
	var lists []*__.Number
	for _, invoice := range taxIdentification {
		lists = append(lists, &__.Number{
			Id:                      invoice.Id,
			Name:                    invoice.Name,
			TaxIdentificationNumber: invoice.TaxIdentificationNumber,
			Address:                 invoice.Address,
			Mobile:                  invoice.Mobile,
			BankOfDeposit:           invoice.BankOfDeposit,
			BankAccount:             invoice.BankAccount,
		})
	}
	return &__.ListTaxIdentificationNumberResp{
		List: lists,
	}, nil
}

// 完善用户信息
func (s *Server) UpdateUser(_ context.Context, in *__.UpdateUserReq) (*__.UpdateUserResp, error) {
	user, err := dao.UpdateUser(in)
	if err != nil {
		return nil, errors.New("完善用户信息失败" + err.Error())
	}
	return &__.UpdateUserResp{
			Id: int32(user.Id),
		},
		nil
}

// 导出数据到CSV/Excel
// ctx: 上下文，用于传递请求范围的值
// in: 导出数据请求参数，包含数据类型、日期范围、用户ID和导出格式
// 返回值: 成功返回包含文件URL、文件名和成功消息的响应，失败返回错误
func (s *Server) ExportData(_ context.Context, in *__.ExportDataReq) (*__.ExportDataResp, error) {
	// 验证请求参数：数据类型不能为空
	if in.DataType == "" {
		return nil, errors.New("数据类型不能为空")
	}

	// 验证请求参数：只支持csv和excel格式的导出
	if in.ExportType != "csv" && in.ExportType != "excel" {
		return nil, errors.New("只支持csv和excel格式的导出")
	}

	// 初始化导出功能，确保导出目录存在
	if err := export.InitExport(); err != nil {
		return nil, errors.New("初始化导出功能失败: " + err.Error())
	}

	// 获取需要导出的数据，调用DAO层方法
	data, err := dao.GetExportData(in.DataType, in.StartDate, in.EndDate, in.UserIds)
	if err != nil {
		return nil, errors.New("获取导出数据失败: " + err.Error())
	}

	// 生成文件名：根据导出类型和数据类型生成唯一文件名
	format := export.ExportFormat(in.ExportType)
	fileName := export.GenerateFileName(in.DataType, format)

	// 执行数据导出：调用export包的导出功能
	filePath, err := export.ExportData(in.DataType, format, fileName, data)
	if err != nil {
		return nil, errors.New("导出数据失败: " + err.Error())
	}

	// 这里简化处理，实际项目中可以将文件上传到文件服务器并返回URL
	// 目前返回文件路径作为示例
	return &__.ExportDataResp{
			FileUrl:  filePath, // 导出文件的路径或URL
			FileName: fileName, // 导出文件的名称
			Message:  "导出成功",   // 操作结果消息
		},
		nil
}

// 个人用户充值记录
func (s *Server) PersonalUserRecharge(_ context.Context, in *__.PersonalUserRechargeReq) (*__.PersonalUserRechargeResp, error) {

	recharge, err := dao.PersonalUserRecharge(in)
	if err != nil {
		return nil, errors.New("创建个人用户充值记录失败: " + err.Error())
	}
	return &__.PersonalUserRechargeResp{
		Id: int32(recharge.Id),
	}, nil
}

// 个人用户退款记录
func (s *Server) PersonalUserRefund(_ context.Context, in *__.PersonalUserRefundReq) (*__.PersonalUserRefundResp, error) {
	refund, err := dao.PersonalUserRefund(in)
	if err != nil {
		return nil, errors.New("创建个人用户退款记录失败: " + err.Error())
	}
	return &__.PersonalUserRefundResp{
		Id: int32(refund.Id),
	}, nil
}

// 个人用户充值记录列表
func (s *Server) PersonalUserRechargeList(_ context.Context, in *__.PersonalUserRechargeListReq) (*__.PersonalUserRechargeListResp, error) {
	resp, err := dao.PersonalUserRechargeList(in)
	if err != nil {
		return nil, errors.New("查询个人用户充值记录失败: " + err.Error())
	}
	return resp, nil
}

// 个人用户退款记录列表
func (s *Server) PersonalUserRefundList(_ context.Context, in *__.PersonalUserRefundListReq) (*__.PersonalUserRefundListResp, error) {
	resp, err := dao.PersonalUserRefundList(in)
	if err != nil {
		return nil, errors.New("查询个人用户退款记录失败: " + err.Error())
	}
	return resp, nil
}

// 导出个人用户充值记录
func (s *Server) ExportPersonalUserRecharge(_ context.Context, in *__.ExportPersonalUserRechargeReq) (*__.ExportDataResp, error) {
	// 验证导出类型
	if in.ExportType != "csv" && in.ExportType != "excel" {
		return nil, errors.New("只支持csv和excel格式的导出")
	}

	// 初始化导出功能
	if err := export.InitExport(); err != nil {
		return nil, errors.New("初始化导出功能失败: " + err.Error())
	}

	// 查询数据
	var recharge models.PersonalUserRecharge
	list, _, err := recharge.GetList(
		in.RechargeTransactionId,
		in.Mobile,
		in.UserName,
		in.RechargeChannel,
		in.StartTime,
		in.EndTime,
		1,
		10000, // 导出时获取所有数据
	)
	if err != nil {
		return nil, errors.New("获取充值记录数据失败: " + err.Error())
	}

	// 转换为导出格式
	var exportData [][]string
	exportData = append(exportData, []string{
		"充值流水号", "用户名", "手机号码", "用户类型", "充值时间",
		"充值金额-本金(元)", "赠送金额(元)", "充值折扣", "第三方流水号", "充值渠道",
	})

	for _, item := range list {
		exportData = append(exportData, []string{
			item.RechargeTransactionId,
			item.UserName,
			item.Mobile,
			item.UserType,
			item.RechargeTime.Format("2006-01-02 15:04:05"),
			item.RechargeAmountPrincipal,
			item.GiftAmount,
			item.RechargeDiscount,
			item.ThirdPartyTransactionId,
			item.RechargeChannel,
		})
	}

	// 生成文件名
	format := export.ExportFormat(in.ExportType)
	fileName := export.GenerateFileName("personal_user_recharge", format)

	// 执行导出
	filePath, err := export.ExportData("personal_user_recharge", format, fileName, exportData)
	if err != nil {
		return nil, errors.New("导出充值记录失败: " + err.Error())
	}

	return &__.ExportDataResp{
		FileUrl:  filePath,
		FileName: fileName,
		Message:  "导出充值记录成功",
	}, nil
}

// 导出个人用户退款记录
func (s *Server) ExportPersonalUserRefund(_ context.Context, in *__.ExportPersonalUserRefundReq) (*__.ExportDataResp, error) {
	// 验证导出类型
	if in.ExportType != "csv" && in.ExportType != "excel" {
		return nil, errors.New("只支持csv和excel格式的导出")
	}

	// 初始化导出功能
	if err := export.InitExport(); err != nil {
		return nil, errors.New("初始化导出功能失败: " + err.Error())
	}

	// 查询数据
	var refund models.PersonalUserRefund
	list, _, err := refund.GetList(
		in.RefundTransactionId,
		in.Mobile,
		in.UserName,
		in.RefundChannel,
		in.StartTime,
		in.EndTime,
		1,
		10000, // 导出时获取所有数据
	)
	if err != nil {
		return nil, errors.New("获取退款记录数据失败: " + err.Error())
	}

	// 转换为导出格式
	var exportData [][]string
	exportData = append(exportData, []string{
		"退款流水号", "用户名", "手机号码", "用户类型", "退款时间",
		"退款金额(元)", "退款原因", "第三方流水号", "退款渠道", "退款状态",
	})

	for _, item := range list {
		exportData = append(exportData, []string{
			item.RefundTransactionId,
			item.UserName,
			item.Mobile,
			item.UserType,
			item.RefundTime.Format("2006-01-02 15:04:05"),
			item.RefundAmount,
			item.RefundReason,
			item.ThirdPartyTransactionId,
			item.RefundChannel,
			item.RefundStatus,
		})
	}

	// 生成文件名
	format := export.ExportFormat(in.ExportType)
	fileName := export.GenerateFileName("personal_user_refund", format)

	// 执行导出
	filePath, err := export.ExportData("personal_user_refund", format, fileName, exportData)
	if err != nil {
		return nil, errors.New("导出退款记录失败: " + err.Error())
	}

	return &__.ExportDataResp{
		FileUrl:  filePath,
		FileName: fileName,
		Message:  "导出退款记录成功",
	}, nil
}
